var appPath = getAppPath();

$(function(){
	initJspGrid();
	initAreaGrid();
	initIncomeGrid();
	initCustGrid();
	initAreaCombo();
	initAddIcDtCombo();
	initBonusLimCombo();
});

// 区域选择
function initAreaCombo(){
	// 检索页面
	// 省
	$("#queryApplyProv").combobox({
		url:appPath+'/itbCom/getAreaForCombo.action?parent=1&blkFlg=1',// 中国
		valueField:'id',
		textField:'name',
		onSelect:function(selProv){
			$("#queryApplyCity").combobox("clear");
			$("#queryApplyDist").combobox("clear");
			$("#queryApplyCity").combobox("loadData",{});
			$("#queryApplyDist").combobox("loadData",{});
			// 市
			var parentId=selProv.id;
			if(Number(parentId)>0){
				$("#queryApplyCity").combobox({
					url:appPath+'/itbCom/getAreaForCombo.action?parent='+parentId+'&blkFlg=1',
					valueField:'id',
					textField:'name',
					onSelect:function(selCity){
						$("#queryApplyDist").combobox("clear");
						$("#queryApplyDist").combobox("loadData",{});
						// 区
						var parentId2=selCity.id;
						if(Number(parentId2)>0){
							$("#queryApplyDist").combobox({
								url:appPath+'/itbCom/getAreaForCombo.action?parent='+parentId2+'&blkFlg=1',
								valueField:'id',
								textField:'name',
								onSelect:function(selDist){
									// TODO
								}
							});
						}
					}
				});
			}
		}
	});
	
	// 编辑页面
	// 省
	$("#addAreaProv").combobox({
		url:appPath+'/itbCom/getAreaForCombo.action?parent=1&blkFlg=1',// 中国
		valueField:'id',
		textField:'name',
		onSelect:function(selProv){
			$("#addAreaCity").combobox("clear");
			$("#addAreaDist").combobox("clear");
			$("#addAreaCity").combobox("loadData",{});
			$("#addAreaDist").combobox("loadData",{});
			// 市
			var parentId=selProv.id;
			if(Number(parentId)>0){
				$("#addAreaCity").combobox({
					url:appPath+'/itbCom/getAreaForCombo.action?parent='+parentId+'&blkFlg=1',
					valueField:'id',
					textField:'name',
					onSelect:function(selCity){
						$("#addAreaDist").combobox("clear");
						$("#addAreaDist").combobox("loadData",{});
						// 区
						var parentId2=selCity.id;
						if(Number(parentId2)>0){
							$("#addAreaDist").combobox({
								url:appPath+'/itbCom/getAreaForCombo.action?parent='+parentId2+'&blkFlg=1',
								valueField:'id',
								textField:'name',
								onSelect:function(selDist){
									// TODO
								}
							});
						}
					}
				});
			}
		}
	});
}

// 选择年/月
function initAddIcDtCombo() {
	var newDt=new Date();
	
	var dataY = [];
	for(var i=2016; i<2100; i++) {
		dataY.push({ "text": i, "id": i });
	}
	$("#addIncomeYear").combobox({
		data: dataY,
		valueField:'id',
		textField:'text',
		onLoadSuccess: function(param) {
			$("#addIncomeYear").combobox('select',newDt.getFullYear()||2017);
        }
	});
	
	var dataM = [];
	for(var i=1; i<=12; i++) {
		dataM.push({ "text": i, "id": i });
	}
	$("#addIncomeMonth").combobox({
		data: dataM,
		valueField:'id',
		textField:'text',
		onLoadSuccess: function(param) {
			$("#addIncomeMonth").combobox('select',newDt.getMonth()+1);
        }
	});
}

// 计算[合伙人奖金]限制条件
function initBonusLimCombo() {
	var dataM = [];
	for(var i=1; i<=10; i++) {
		dataM.push({ "text": i+'人', "id": i });
	}
	$("#addIncomeBonusLim").combobox({
		data: dataM,
		valueField:'id',
		textField:'text',
		onLoadSuccess: function(param) {
			$("#addIncomeBonusLim").combobox('select',3);
        }
	});
}

// 合伙人列表初始化
function initJspGrid(){
	
	$('#partnerGrid').datagrid({
	    url:appPath + "/itbCom/getPartnerInfoPg.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'partner_id',title:'合伙人ID',width:35,align:'center',sortable:false},
	        {field:'level',title:'级别',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.partner_id) return "N/A";
	        		var show = '<span style="color:red">未知</span>';
	        		switch(Number(value||'0')){
		        		case 10: show="普通"; break;
		        		case 20: show='<span style="color:red">高级</span>'; break;
		        	}
	        		return "<a href='javascript:void(0)' onClick='editLevel("+rowData.partner_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'user_id',title:'用户ID',width:35,align:'center',sortable:false},
	        {field:'area',title:'管辖区域',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.partner_id) return "N/A";
	        		var show = '<span style="color:red">未知</span>';
	        		switch(Number(rowData.level||'0')){
		        		case 10: show="不限"; break;
		        		case 20: show="<a href='javascript:void(0)' onClick='showArea("+
		        			rowData.partner_id+",\""+rowData.name+"\")'>详情("+rowData.areaCnt+")</a>"; break;
		        	}
	        		return show;
	        	}
		    },
//	        {field:'organize',title:'机构名称',width:70,align:'center',sortable:false},
	        {field:'name',title:'姓名',width:50,align:'center',sortable:false},
	        {field:'mobile',title:'预留电话',width:40,align:'center',sortable:false},
	        {field:'user_mobile',title:'注册手机',width:50,align:'center',sortable:false},
//	        {field:'email',title:'邮箱',width:65,align:'center',sortable:false},
//	        {field:'qq',title:'QQ',width:50,align:'center',sortable:false},
	        {field:'address',title:'申请地址',width:55,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		return (rowData.prov_name||'')+(rowData.city_name||'')+(rowData.dist_name||'');
	        	}
	        },
	        {field:'cust',title:'下线用户',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.partner_id) return "N/A";
	        		return "<a href='javascript:void(0)' onClick='showCust("+
        				rowData.user_id+","+rowData.partner_id+",\""+rowData.name+"\")'>("+rowData.custCnt+")人</a>";
	        	}
		    },
	        {field:'income',title:'收益',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.partner_id) return "N/A";
	        		return "<a href='javascript:void(0)' onClick='showIncome("+
        				rowData.user_id+","+rowData.partner_id+",\""+rowData.name+"\")'>明细</a>";
	        	}
		    },
	        {field:'bank',title:'开户行',width:50,align:'center',sortable:false},
	        {field:'bank_account',title:'银行账户',width:50,align:'center',sortable:false},
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
				text:'删除合伙人',
				iconCls:'icon-cancel',
				handler:function(){
					delPartner();
				}
			}
		]
	});
}

// 管辖区域列表
function initAreaGrid(){
	$('#areaGrid').datagrid({
		url:appPath + "/itbCom/getPartnerAreaInfoPg.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam2(),
	    singleSelect:true,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'pa_id',title:'区域ID',width:30,align:'left',sortable:false},
	        {field:'prov',title:'省',width:40,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pa_id) return '<span style="color:red;">N/A</span>';
	        		return rowData.prov_name||'<span style="color:red;">所有省</span>';
	        	}
		    },
	        {field:'city',title:'市',width:30,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pa_id) return '<span style="color:red;">N/A</span>';
	        		return rowData.city_name||'<span style="color:red;">所有市</span>';
	        	}
		    },
	        {field:'dist',title:'区',width:30,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pa_id) return '<span style="color:red;">N/A</span>';
	        		return rowData.dist_name||'<span style="color:red;">所有区</span>';
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:30,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:30,align:'center',sortable:false}
	    ]],
	    hideColumn:['partner_id'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
				text:'添加区域',
				iconCls:'icon-add',
				handler:function(){
					showAddAreaDlg();
				}
			},
			{
	        	text:'删除区域',
				iconCls:'icon-cancel',
				handler:function(){
					delArea();
				}
	        }
        ]
	});
}

// 收益列表
function initIncomeGrid(){
	$('#incomeGrid').datagrid({
		url:appPath + "/itbCom/getPartnerIncomeInfoPg.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam3(),
	    singleSelect:true,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'id',title:'项目ID',width:30,align:'left',sortable:false},
	        {field:'state',title:'状态',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.id) return "N/A";
	        		var show = '<span style="color:red">未知</span>';
	        		switch(Number(value||'0')){
		        		case 10: show="新建"; break;
		        		case 20: show='<span style="color:red">发放失败</span>'; break;
		        		case 30: show='<span style="color:blue">纠纷中</span>'; break;
		        		case 40: show='<span style="color:green">发放成功</span>'; break;
		        	}
	        		return "<a href='javascript:void(0)' onClick='editIcState("+
	        			rowData.id+","+rowData.state+")'>"+show+"</a>";
	        	}
		    },
	        {field:'year',title:'年份',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.id || !value) return "N/A";
  	        		return value;
	        	}
		    },
	        {field:'month',title:'月份',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.id || !value) return "N/A";
  	        		return value;
	        	}
		    },
//	        {field:'day',title:'日',width:30,align:'left',sortable:false,
//  	        	formatter:function(value, rowData, rowIndex){
//  	        		if(!rowData.id || !value) return "N/A";
//  	        		return value;
//	        	}
//		    },
	        {field:'income',title:'总收益',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.id) return "N/A";
  	        		return '<span style="color:red">'+(Number(value||'0')/100)+'</span>' + ' 元';
	        	}
		    },
	        {field:'income_base',title:'基本收益',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.id) return "N/A";
  	        		return '<span style="color:blue">'+(Number(value||'0')/100)+'</span>' + ' 元';
	        	}
		    },
	        {field:'income_extra',title:'额外收益',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.id) return "N/A";
  	        		return '<span style="color:green">'+(Number(value||'0')/100)+'</span>' + ' 元';
	        	}
		    },
	        {field:'income_bonus',title:'奖励',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.id) return "N/A";
  	        		return '<span style="color:orange">'+(Number(value||'0')/100)+'</span>' + ' 元';
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_id'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
	        	text:'删除收益',
				iconCls:'icon-cancel',
				handler:function(){
					delIncome();
				}
	        },
			'-',
			{
				text:'添加收益',
				iconCls:'icon-add',
				handler:function(){
					showAddIncomeDlg();
				}
			}
        ]
	});
}

// 下线用户列表
function initCustGrid(){
	$('#custGrid').datagrid({
		url:appPath + "/itbCom/getPartnerCustInfoPg.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam4(),
	    singleSelect:true,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'pc_id',title:'ID',width:25,align:'left',sortable:false},
	        {field:'user_id',title:'用户ID',width:30,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pc_id || !value) return "N/A";
	        		return '<span style="color:red">'+value+'</span>';
	        	}
		    },
	        {field:'user_name',title:'用户名',width:40,align:'left',sortable:false},
	        {field:'user_nickname',title:'用户昵称',width:40,align:'left',sortable:false},
	        {field:'mobile',title:'注册手机',width:40,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pc_id || !value) return "N/A";
	        		return '<span style="color:blue">'+value+'</span>';
	        	}
		    },
	        {field:'start_time',title:'有效开始日',width:40,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pc_id || !value) return "N/A";
	        		return '<span style="color:green">'+value.substr(0,10)+'</span>';
	        	}
		    },
	        {field:'end_time',title:'有效截止日',width:40,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pc_id || !value) return "N/A";
	        		return '<span style="color:green">'+value.substr(0,10)+'</span>';
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
	        	text:'删除下线用户',
				iconCls:'icon-cancel',
				handler:function(){
					$.messager.alert('提示信息','待开发...','info');
					//delCust();
				}
	        }
        ]
	});
}

// 编辑等级
function editLevel(id){
	$("#levelDlg").show();
	$('#levelForm').form('clear');

	$("#updId").val(id);
	
	var url = appPath + "/itbCom/getPartnerInfoLst.action?id="+id;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#updPartnerLevel").combobox('select',info.level||10);
		}
	});
	
	$("#levelBtn").show();
	$('#levelDlg').window({
		title:'合伙人级别',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#levelDlg').window('move',{top:20,left:20});
	$('#levelDlg').window('open');
}

function cancelUpdLevel(){
	$('#levelDlg').window('close');
}
function doUpdLevel(){
	var id = $("#updId").val();
	var level = $("#updPartnerLevel").combobox('getValue');
	
	var url = appPath+"/itbComWeb/updPartner.action";
	var sendData = {
		"partnerInfo.partner_id": Number(id||"0"),
		"partnerInfo.level": Number(level||"10")
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','提交成功','info');
			$('#levelDlg').window('close');
			doQuery();
        } else {
        	$.messager.alert('提示信息','提交失败','info');
        }
    });
}

function delPartner(){
	var selectItem=$("#partnerGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择合伙人！','warning');
		return;
	}
//	for(var i=0; i<selectItem.length; i++){
//		if(Number(selectItem[i].state||'0')==20){
//			$.messager.alert('提示信息','不能删除[审核中]申请！','warning');
//			return;
//		}
//	}
	
	$.messager.confirm("确认", "是否确认[删除]所选合伙人？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.partner_id + ",";
				});
				var url = appPath+"/itbComWeb/delPartner.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

// 打开管辖区域窗口
function showArea(pId,pNm){
	$('#areaForm').form('clear');
	$("#showAreaPId").html(pId||'');
	$("#showAreaPNm").html(pNm||'');
	$("#areaPartnerId").val(pId);
	
	doQuery2();
	
	$("#areaBtn").show();
	$('#areaDlg').window({
		title:'管辖区域详情',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#areaDlg').window('move',{top:20,left:20});
	$('#areaDlg').window('open');
}
function closeArea() {
	$('#areaDlg').window('close');
}

// 删除管辖区域
function delArea(){
	var selectItem=$("#areaGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择区域项目！','warning');
		return;
	}
	
	$.messager.confirm("确认", "是否确认[删除]所选管辖区域？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.pa_id + ",";
				});
				var url = appPath+"/itbComWeb/delPartnerArea.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery2();
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

// 添加管辖区域
function showAddAreaDlg(){
	$("#addAreaBtn").show();
	$('#addAreaDlg').window({
		title:' 添加管辖区域',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#addAreaDlg').window('move',{top:20,left:20});
	$('#addAreaDlg').window('open');
}
function cancelAddArea(){
	$('#addAreaDlg').window('close');
}
function doAddArea(){
	var provId =$("#addAreaProv").combobox('getValue');
	var cityId =$("#addAreaCity").combobox('getValue');
	var distId =$("#addAreaDist").combobox('getValue');
	
	if(!provId || Number(provId||'0')<=100000) {
		return $.messager.alert('提示信息','请选择省会！','info');
	}

	var pId = $("#areaPartnerId").val();

	var url = appPath+"/itbComWeb/addPartnerArea.action";
	var sendData = {
			"partnerAreaInfo.partner_id":pId,
			"partnerAreaInfo.prov":provId,
			"partnerAreaInfo.city":cityId,
			"partnerAreaInfo.dist":distId
	}
	$.post(url,sendData,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','管辖区域已添加！','info');
			doQuery2();
			doQuery();
		} else if(data=="exist") {
			$.messager.alert('提示信息','该区域已被分配！','info');
		}else{
			$.messager.alert('提示信息','添加失败！','info');
		}
	});
}

// 编辑收益状态
function editIcState(id,st){
	$("#icStateDlg").show();
	$('#icStateForm').form('clear');

	$("#updIcId").val(id);
	$("#updIcState").combobox('select', st||10);
	
	$("#icStateBtn").show();
	$('#icStateDlg').window({
		title:'收益状态',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#icStateDlg').window('move',{top:20,left:20});
	$('#icStateDlg').window('open');
}

function cancelUpdIcState(){
	$('#icStateDlg').window('close');
}
function doUpdIcState(){
	var id = $("#updIcId").val();
	var st = $("#updIcState").combobox('getValue');
	
	var url = appPath+"/itbComWeb/updPartnerIncome.action";
	var sendData = {
		"partnerIncomeInfo.id": Number(id||"0"),
		"partnerIncomeInfo.state": Number(st||"10")
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','提交成功','info');
			$('#icStateDlg').window('close');
			doQuery3();
        } else {
        	$.messager.alert('提示信息','提交失败','info');
        }
    });
}

// 打开收益窗口
function showIncome(uId,pId,pNm){
	$('#incomeForm').form('clear');
	$("#showIncomePId").html(pId||'');
	$("#showIncomePNm").html(pNm||'');
	
	$("#incomeUId").val(uId);
	$("#incomePId").val(pId);
	
	doQuery3();
	
	$("#incomeBtn").show();
	$('#incomeDlg').window({
		title:'合伙人收益详情',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#incomeDlg').window('move',{top:20,left:20});
	$('#incomeDlg').window('open');
}
function closeIncomeDlg() {
	$('#incomeDlg').window('close');
}

// 删除收益项目
function delIncome(){
	var selectItem=$("#incomeGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择收益项目！','warning');
		return;
	}
	
	$.messager.confirm("确认", "是否确认[删除]所选收益项目？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.id + ",";
				});
				var url = appPath+"/itbComWeb/delPartnerIncome.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery3();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

// 添加收益项目
function showAddIncomeDlg(){
	$("#addIncomeBase").val(0);
	$("#addIncomeExtra").val(0);
	$("#addIncomeBonus").val(0);
	$("#addIncomeDesc").val('');
	var pId=document.getElementById('showIncomePId').innerText;
	$("#partId").val(pId);
	$("#addIncomeBtn").show();
	$('#addIncomeDlg').window({
		title:' 添加月收益项目',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#addIncomeDlg').window('move',{top:20,left:20});
	$('#addIncomeDlg').window('open');
}
function cancelAddIncome(){
	$('#addIncomeDlg').window('close');
}
function doAddIncome(){
	var year =$("#addIncomeYear").combobox('getValue');
	var month =$("#addIncomeMonth").combobox('getValue');
	var desc =$("#addIncomeDesc").val();
	var incomeBase =Number($("#addIncomeBase").val()||'0')||0;
	var incomeExtra =Number($("#addIncomeExtra").val()||'0')||0;
	var incomeBonus =Number($("#addIncomeBonus").val()||'0')||0;
	var income = incomeBase+incomeExtra+incomeBonus;
	
	var pId = $("#incomePId").val();
	
	if(income<0) {
		return $.messager.alert('提示信息','请填写正确收益数值！','info');
	}

	var url = appPath+"/itbComWeb/addPartnerIncome.action";
	var sendData = {
			"partnerIncomeInfo.partner_id":pId,
			"partnerIncomeInfo.year":year,
			"partnerIncomeInfo.month":month,
			"partnerIncomeInfo.income_base":incomeBase,
			"partnerIncomeInfo.income_extra":incomeExtra,
			"partnerIncomeInfo.income_bonus":incomeBonus,
			"partnerIncomeInfo.income":income,
			"partnerIncomeInfo.desc":desc||''
	}
	$.post(url,sendData,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','收益项目添加成功！','info');
			doQuery3();
		}else{
			$.messager.alert('提示信息','添加失败！','info');
		}
	});
}

// 计算参考收益
function doCalIncome(){
	var year =$("#addIncomeYear").combobox('getValue');
	var month =$("#addIncomeMonth").combobox('getValue');
	var pId = $("#incomePId").val();
	
	$("#addIncomeBase").val(0);
	$("#addIncomeExtra").val(0);

	var url = appPath+"/itbCom/calPartnerIncome.action";
	var sendData = {
			"partnerIncomeInfo.partner_id":pId,
			"partnerIncomeInfo.year":year,
			"partnerIncomeInfo.month":month
	}
	$.post(url,sendData,function(ret){
		if(ret && ret.partner_id){
			var baseV = Number(ret.income_base||'0')||0;
			var exV = Number(ret.income_extra||'0')||0;
			$("#addIncomeBase").val(baseV);
			$("#addIncomeExtra").val(exV);
			$.messager.alert('提示信息','参考[基本收益]金额: <span style="color:red">'+(baseV/100)+'</span>元'+
					'</br>参考[额外收益]金额: <span style="color:red">'+(exV/100)+'</span>元','info');
		}else{
			$.messager.alert('提示信息','计算失败！','info');
		}
	});
}

/**
 * 月订单明细 收益信息
 */
function initRatio(){
	$('#ratioGrid').datagrid({
	    url:appPath+"/itbpod/getPartnerOrderInf.action",
	    queryParams: getRatioParm(),
	    height:'80',
	    striped:true,
	    fitColumns:true,
	    fit:true,
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    columns:[[
  	        {field:'orderId',title:'订单ID',width:50,align:'center',sortable:false},
	        {field:'time',title:'日期',width:80,align:'center',sortable:false},
	        {field:'mobile',title:'手机号',width:80,align:'center',sortable:false},
	        {field:'orderAmount',title:'订单金额',width:70, align:'right',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		return '<span style="color:#0000FF">'+(Number(value||'0')/100)+'</span> 元';
	        	}
	        },
	        {field:'incomeBase',title:'收益',width:70, align:'right',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		return '<span style="color:#FF0000">'+(Number(value||'0')/100)+'</span> 元';
	        	}
	        }
	    ]],
	    hideColumn:['type'],
	    pagination:true,
		rownumbers:true
	});
}
// 跳转到订单列表
function goIncomeLst() {
	$("#ratioGrid").html('');
	$('#ratio').window({
		title:'订单收益明细',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$('#ratio').window('move',{top:20,left:20});
	$('#ratio').window('open');
	initRatio();
}

/**	 
 * 城市合伙人订单明细所需参数
 */
function getRatioParm(){
	var obj={};
	var year =$("#addIncomeYear").combobox('getValue');
	var month =$("#addIncomeMonth").combobox('getValue');
	var uId = $("#incomeUId").val();
	if(uId && uId.length>0) obj.uId=uId;
	var startDt = $.DateUtil.format((new Date(year,month-1,1)),'yyyy-MM-dd');
	if(startDt && startDt.length>0) obj.startDt=startDt;
	var endDt = getLastDay(year, month);
	if(endDt && endDt.length>0) obj.endDt=endDt;
	return obj;
}

// 打开下线用户列表窗口
function showCust(uId,pId,pNm){
	$('#custForm').form('clear');
	$("#showCustPId").html(pId||'');
	$("#showCustPNm").html(pNm||'');

	$("#custPId").val(pId);
	
	doQuery4();
	
	$("#custBtn").show();
	$('#custDlg').window({
		title:'合伙人下线用户详情',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#custDlg').window('move',{top:20,left:20});
	$('#custDlg').window('open');
}
function closeCustDlg() {
	$('#custDlg').window('close');
}


// 查看销售排行
function chkRank(){
	$("#rankGrid").html('');
	$("#rank").window({
		title:'销售排行榜',
		minimizable:false,
		maximizable:true,
		draggable:true,
		shadow:true,
		modal:true
	});
	$("#rank").window('open');
	$("#rank").window('move',{top:20,left:20});
	var pId=$("#partId").val();
	initRank(pId);
	calPartnerBonus(pId);
}

// 计算奖金
function calPartnerBonus(pId){
	var year =$("#addIncomeYear").combobox('getValue');
	var month =$("#addIncomeMonth").combobox('getValue');
	var lim = $("#addIncomeBonusLim").combobox('getValue');
	var uId=$("#incomeUId").val();
	var pId = $("#incomePId").val();
	
	$("#addIncomeBonus").val(0);

	var url = appPath+"/itbpod/calPartnerBonus.action";
	var sendData = {
			"partnerIncomeInfo.partner_id":pId,
			"partnerIncomeInfo.user_id":uId,
			"partnerIncomeInfo.year":year,
			"partnerIncomeInfo.month":month,
			"partnerIncomeInfo.bonusLim":lim
	}
	$.post(url,sendData,function(ret){
		if(ret && ret.partner_id){
			var bonus = Number(ret.income_bonus||'0')||0;
			$("#addIncomeBonus").val(bonus);
			$.messager.alert('提示信息','参考[奖金]金额: <span style="color:red">'+(bonus/100)+'</span>元','info');
		}else{
			$.messager.alert('提示信息','计算[奖金]金额失败！','info');
		}
	});
}



/**
 * 获取排行信息 需要参数
 */
function getRankParm(){
	var obj={};
	var year=$("#addIncomeYear").combobox('getValue');
	var month=$("#addIncomeMonth").combobox('getValue');
	var uId=$("#incomeUId").val();
	if(year && year.length>0) obj.year=year;
	if(month && month.length>0) obj.month=month;
	if(uId && uId.length>0) obj.uId=uId;
	return obj;
}

/**
 * 加载销售排行
 */
function initRank(id){
	$("#rankGrid").datagrid({
		url:appPath+"/itbpod/getPartnerSaleRank.action",
		queryParams:getRankParm(),
	    height:'80',
	    striped:true,
	    fitColumns:true,
	    fit:true,
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    columns:[[
	            {field:'rank',title:'排名',width:30,align:'center',sortable:false,
	            	formatter:function(value,rowData,rowIndex){
	            		if(id==rowData.partnerId){
	            			return '<span style="color:red;">'+value+'</span>';
	            		}else{
	            			return value;
	            		}
	            	}  
	            },
	  	        {field:'year',title:'年份',width:20,align:'center',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	  	        		return value;
  	        		}
	  	        },
	  	        {field:'month',title:'月份',width:20,align:'center',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	  	        		return value;
  	        		}
	  	        },
	  	        {field:'pname',title:'省会',width:40,align:'center',sortable:false,
	            	formatter:function(value,rowData,rowIndex){
	  	        		return value;
  	        		}
	  	        },
	  	        {field:'cname',title:'市区',width:40,align:'center',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	  	        		return value;
  	        		}
	  	        },
	  	        {field:'dname',title:'城区',width:40,align:'center',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	  	        		return value;
  	        		}
	  	        },
	  	        {field:'partnerId',title:'合伙人ID',width:30,align:'center',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	            		  if(id==rowData.partnerId){
	            			  return '<span style="color:red;">'+value+'</span>';
	            		  }else{
	            			  return value;
	            		  }
	            	  }
	  	        },
	  	        {field:'mobile',title:'手机号',width:40,align:'center',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	            		  if(id==rowData.partnerId){
	            			  return '<span style="color:red;">'+value+'</span>';
	            		  }else{
	            			  return value;
	            		  }
	            	  }
	  	        },
	  	        {field:'saleFee',title:'销售额',width:30, align:'right',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	  	        		if(value){
	  	        			return '<span style="color:blue;">'+(value)/100+' 元</span>';
	  	        		}else{
	  	        			return '';
	  	        		}
	  	        	}
	  	        },
	  	        {field:'income',title:'收入',width:30, align:'right',sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	  	        		if(value){
	  	        			return '<span style="color:green;">'+(value)/100+' 元</span>';
	  	        		}else{
	  	        			return '';
	  	        		}
	  	        	}
	  	        },
	  	        {field:'desc',title:'备注信息',width:40, align:'center', sortable:false,
	  	        	formatter:function(value,rowData,rowIndex){
	  	        		return value||'';
	  	        	}
	  	        },
	  	        {field:'create_time',title:'创建时间', width:70, align:'center', sortable:false},
	  	        {field:'update_time',title:'修改时间', width:70, align:'center', sortable:false}
	  	    ]],
		pagination:true,
		rownumbers:true			
	});
}


/** 
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	
	var findLevel = $("#queryPartnerLevel").combobox('getValue');
	var findName = $("#queryPartnerName").val();
	var findMobile = $("#queryPartnerMobile").val();
	var findProv = $("#queryApplyProv").combobox('getValue');
	var findCity = $("#queryApplyCity").combobox('getValue');
	var findDist = $("#queryApplyDist").combobox('getValue');
	var findCustFlg = $("#queryHasCust").combobox('getValue');
	
	
	if(findLevel && Number(findLevel||'0')>0) queryObject.findPartnerLevel = findLevel;// 级别
	if(findName && findName.length>0) queryObject.findPartnerName = findName;// 姓名
	if(findMobile && Number(findMobile||'0')>0) queryObject.findPartnerMobile = findMobile;// 手机
	if(findProv && Number(findProv||'0')>0) queryObject.findApplyProv = findProv;// 申请省
	if(findCity && Number(findCity||'0')>0) queryObject.findApplyCity = findCity;// 申请市
	if(findDist && Number(findDist||'0')>0) queryObject.findApplyDist = findDist;// 申请区
	if(findCustFlg && Number(findCustFlg||'0')>0) queryObject.findHasCustFlg = findCustFlg;// 是否存在下线
	
	return queryObject;
}

function getQueryParam2(){
	var queryObject = {};
	
	var findPId = $("#areaPartnerId").val();
	
	if(findPId && Number(findPId||'0')>0) queryObject.findPartnerId = findPId;
	
	return queryObject;
}

function getQueryParam3(){
	var queryObject = {};
	
	var findPId = $("#incomePId").val();
	
	if(findPId && Number(findPId||'0')>0) queryObject.findPartnerId = findPId;
	
	return queryObject;
}

function getQueryParam4(){
	var queryObject = {};
	
	var findPId = $("#custPId").val();
	
	if(findPId && Number(findPId||'0')>0) queryObject.findPartnerId = findPId;
	
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#partnerGrid").datagrid('unselectAll');
	$("#partnerGrid").datagrid('load', getQueryParam());
}
function doQuery2(){
	$("#areaGrid").datagrid('unselectAll');
	$("#areaGrid").datagrid('load', getQueryParam2());
}
function doQuery3(){
	$("#incomeGrid").datagrid('unselectAll');
	$("#incomeGrid").datagrid('load', getQueryParam3());
}
function doQuery4(){
	$("#custGrid").datagrid('unselectAll');
	$("#custGrid").datagrid('load', getQueryParam4());
}

function getLastDay(y,m) {
	var dt = new Date(y,m,1);
	var cdt = new Date(dt.getTime()-1000*3600*24);
	return $.DateUtil.format(cdt,'yyyy-MM-dd');
}